﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// IP 的摘要说明
/// </summary>
public class IPMethod
{
	 
		/// <summary>
     /// 获取客户端IP地址（无视代理）
    /// </summary>
     /// <returns>若失败则返回回送地址</returns>
      public string GetHostAddress()
     {
        string userHostAddress = HttpContext.Current.Request.UserHostAddress;

         if (string.IsNullOrEmpty(userHostAddress))
        {
            userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
       }
 
        //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
         if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
        {
            return userHostAddress;
         }
         return "127.0.0.1";
    }

 
     /// <summary>
     /// 检查IP地址格式
     /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public bool IsIP(string ip)
     {
        return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
     }

    public string IPGetCity(string ip)  
       {  
           try  
           {
               StringBuilder str = new StringBuilder();
               WebClient MyWebClient = new WebClient();  
               MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据  
               Byte[] pageData = MyWebClient.DownloadData("http://ip.taobao.com/service/getIpInfo.php?ip=" +ip); //从指定网站下载数据  
               string pageHtml = Encoding.Default.GetString(pageData);  
               //Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(pageHtml);  
               // if (dic["code"].ToString() == "0")  
               // {  
               //     Dictionary<string, object> dic_data = (Dictionary<string, object>)dic["data"];  
               //     return dic_data;  
               // }             
               JObject jofirst = JObject.Parse(pageHtml);
               string data = jofirst["data"].ToString();
               JObject joSecond = JObject.Parse(data);
               str.Append(joSecond["region"] + "-" + joSecond["city"] + "-" + joSecond["county"]);
               return str.ToString();

            }  
            catch (WebException webEx)  
            {  
            }  
            return null;  
        }

    /// <summary>
    /// 返回jobject形式 具体由程序员自主选择
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public JObject IPGetProviceCity(string ip)
    {
        try
        {
            StringBuilder str = new StringBuilder();
            WebClient MyWebClient = new WebClient();
            MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据  
            Byte[] pageData = MyWebClient.DownloadData("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip); //从指定网站下载数据  
            string pageHtml = Encoding.Default.GetString(pageData);
                         
            JObject jofirst = JObject.Parse(pageHtml);
            string data = jofirst["data"].ToString();
            JObject joSecond = JObject.Parse(data);
            return joSecond;
        }
        catch (WebException webEx)
        {
        }
        return null;
    }  
	}
 
 
 